package com.roamer.school.common.util;

import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5 工具类
 *
 * @author roamer
 * @version V1.0
 * @date 2019/1/7 14:32
 */
public abstract class Md5Utils {

    public static final int STRING_LENGTH = 32;

    /**
     * MD5编码
     *
     * @param charset 字符集
     * @param origin  字符
     *
     * @return 编码后的16进制字符
     */
    public static String md5Encode(final Charset charset, String origin) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            if (null == charset) {
                return byteArrayToHexString(md.digest(origin.getBytes()));
            }
            return byteArrayToHexString(md.digest(origin.getBytes(charset)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Creat messageDigest instance failed", e);
        }
    }


    /**
     * 转为32位16进制字符串
     *
     * @param bytes 字节数组
     *
     * @return 16进制字符串
     */
    private static String byteArrayToHexString(byte[] bytes) {
        String sb = new BigInteger(1, bytes).toString(16);
        StringBuilder resultSb = new StringBuilder(sb);
        while (resultSb.length() < STRING_LENGTH) {
            resultSb.insert(0, "0");
        }
        return resultSb.toString();
    }

}
